package com.platform.modules.mall.activityV2.rule;

import com.platform.common.exception.BusinessException;
import com.platform.common.utils.JedisUtil;
import com.platform.modules.mall.activityV2.entity.ParticipantBo;
import com.platform.modules.mall.activityV2.entity.WinnerBo;
import com.platform.modules.mall.entity.MallGoodsEntity;
import com.platform.modules.mall.entity.MallGoodsToActivityEntity;
import com.platform.modules.mall.service.MallGoodsService;
import com.platform.modules.mall.service.MallGoodsToActivityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Slf4j
@Component("pollingGoodsRule")
public class PollingGoodsRule implements RuleInterface{

    private static final String KEY="PollingGoodsRule:Index:";

    @Autowired
    private JedisUtil jedisUtil;

    @Autowired
    private MallGoodsService mallGoodsService;

    @Autowired
    private MallGoodsToActivityService mallGoodsToActivityService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WinnerBo execute(ParticipantBo bo) {

        List<MallGoodsToActivityEntity> list = bo.getList();
        int num=list.size();
        MallGoodsEntity goods =null;

        for (int i=0;i<num;i++){
            Long incr = jedisUtil.incr(KEY+bo.getActivityId());
            long index =incr % num;
            MallGoodsToActivityEntity entity = list.get((int)index);

            boolean bool = mallGoodsToActivityService.deductionNumber(entity.getId(), bo.getRequestNum());
            if (!bool){
                log.info("该商品={}在活动中库存不足，跳到下一个商品",entity.getGoodsId());
                continue;
            }

            goods = mallGoodsService.shoppingNotException(entity.getGoodsId(), bo.getRequestNum(), null);
            if (goods==null){
                log.info("商品={}库存不足，跳到下一个商品",goods.getId());
                continue;
            }
        }
        if (goods==null){
            throw new BusinessException("活动中没有合适的商品");
        }

        WinnerBo winnerBo =new WinnerBo();
        winnerBo.setGoodsEntity(goods);
        winnerBo.setNum(bo.getNum()-bo.getRequestNum());
        winnerBo.setList(list);
        return winnerBo;
    }
}
